package com.yuanxin.yuanxinwebview;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebChromeClient;

import java.io.File;

/**
 * Created by lemon on 16/8/11.
 */
public class YuanXinWebViewImageActivity extends Activity {
    private static final int FILECHOOSER_RESULTCODE = 1006;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(
                Intent.createChooser(i, "选择文件"),
                FILECHOOSER_RESULTCODE);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE&&resultCode==RESULT_OK) {
            if (YuanXinWebViewCommon.filePathCallback != null) {
                Uri[] uris = WebChromeClient.FileChooserParams.parseResult(resultCode, data);
                Uri[]newUris=new Uri[uris.length];
                for (int i=0;i<uris.length;i++) {
                    String path = FileUtils.getPath(this, uris[i]);
                    if(TextUtils.isEmpty(path)){
                        return;
                    }
                    Uri newUri= Uri.fromFile(new File(path));
                    newUris[i]=newUri;
                   // Log.v("YuanXinWebViewImage",newUri.toString());
                }
                YuanXinWebViewCommon.filePathCallback.onReceiveValue(newUris);
                YuanXinWebViewCommon.filePathCallback = null;
            } else if (YuanXinWebViewCommon.uploadMsg != null) {
                Uri result = data == null || resultCode != RESULT_OK ? null
                        : data.getData();
                String path = FileUtils.getPath(this, result);
                if(TextUtils.isEmpty(path)){
                    return;
                }
                Uri newUri=Uri.fromFile(new File(path));
               // Log.v("YuanXinWebViewImage",newUri.toString());
                YuanXinWebViewCommon.uploadMsg.onReceiveValue(newUri);
                YuanXinWebViewCommon.uploadMsg = null;
            }
        }
        this.finish();
    }
}
